﻿@page "/bloggers"
@using Microsoft.Extensions.Localization
@using Snow.Blog.Model.Enum;
@using Snow.Blog.Common.Exceptions;
@using Snow.Blog.Web.Admin.Middleware.Wrappers;
@using Snow.Blog.Service.Dto;
@using Snow.Blog.Service.Bloggers;
@using Snow.Blog.Service.Bloggers.Dto;
@using Snow.Blog.Service.Enums;
@using Snow.Blog.Service.Categories;
@using Snow.Blog.Service.Categories.Dto;

@inject IMatToaster matToaster
@inject HttpClient Http
@inject IBloggerService _bloggerService
@inject ICategoryService _categoryService
@inject IEnumService _enumService

<MatTable Items="@bloggers" class="mat-elevation-z5" PageParamName="ask就">
    <MatTableHeader>
        <th><MatButton Icon="add" Label="New Blogger" OnClick="@(() => OpenUpsertBloggerDialog())"></MatButton></th>
        <th>Title</th>
        <th>Description</th>
        <th>CategoryName</th>
    </MatTableHeader>
    <MatTableRow Context="BloggerRow">
        <td>
            <div style="width:155px;">
                <MatIconButton Icon="edit" OnClick="@(() => OpenUpsertBloggerDialog(BloggerRow.Id))"></MatIconButton>
                <MatIconButton Icon="delete" OnClick="@(() => OpenDeleteDialog(BloggerRow.Id, BloggerRow.Title))"></MatIconButton>
            </div>
        </td>
        <td><div style="width:300px;">@BloggerRow.Title</div></td>
        <td><div style="width: 400px;">@BloggerRow.Description</div></td>
        <td>@BloggerRow.CategoryName</td>
    </MatTableRow>
</MatTable>
<MatDialog @bind-IsOpen="@UpsertBloggerDialogOpen">
    <MatDialogTitle>
        @labelUpsertDialogTitle
    </MatDialogTitle>
    <MatDialogContent>
        @*<MatTextField @bind-Value="editDto.Id" Disabled="@isCurrentBloggerReadOnly"></MatTextField>*@
        <fieldset>
            <div class="form-group">
                <MatTextField @bind-Value="editDto.Title" Label="Title" FullWidth="true" Required="true"></MatTextField>
            </div>
        </fieldset>
        <div class="form-group">
            <MatSelect Label="Category"
                       @bind-Value="editDto.CategoryId"
                       TValue="int">
                <MatOption TValue="int" Value="-1">请选择</MatOption>
                @foreach (var item in categoriesSelections)
                {
                    <MatOption TValue="int" Value="@item.Key">
                        @item.Value
                    </MatOption>
                }
            </MatSelect>
        </div>
        <div class="form-group">
            <MatSelect Label="SourceType" @bind-Value="editDto.SourceType" TValue="int">
                <MatOption TValue="int" Value="-1">请选择</MatOption>
                @foreach (var item in sourceTypesSelections)
                {
                    <MatOption TValue="int" Value="@item.Key">
                        @item.Value
                    </MatOption>
                }
            </MatSelect>
        </div>
        <div class="form-group">
            <MatNumericUpDownField Label="Sort"
                                   @bind-Value=@sort
                                   FullWidth="true"
                                   DecimalPlaces=0
                                   Minimum=0
                                   Maximum="@int.MaxValue">
            </MatNumericUpDownField>
        </div>
        <div class="form-group">
            <MatTextField @bind-Value="editDto.Description" Label="Description" TextArea="true" FullWidth="true" Dense="true"></MatTextField>
        </div>
        <div class="form-group">
            <MatTextField @bind-Value="editDto.HtmlEncoded" Label="Content" TextArea="true" FullWidth="true" Dense="true"></MatTextField>
        </div>
    </MatDialogContent>
    <MatDialogActions>
        <MatButton OnClick="@(e => { UpsertBloggerDialogOpen = false; })">Cancel</MatButton>
        <MatButton OnClick="@UpsertBloggerAsync">@labelUpsertDialogOkButton</MatButton>
    </MatDialogActions>
</MatDialog>
<MatDialog @bind-IsOpen="@isDeleteBloggerDialogOpen" Style="z-index:100">
    <MatDialogTitle><MatIcon Icon="warning"></MatIcon> Confirm Delete</MatDialogTitle>
    <MatDialogContent>
        Are you sure you want to delete the role "@currentBloggerName" ?
    </MatDialogContent>
    <MatDialogActions>
        <MatButton OnClick="@(e => { isDeleteBloggerDialogOpen = false; })">Cancel</MatButton>
        <MatButton OnClick="@DeleteBloggerAsync">Delete</MatButton>
    </MatDialogActions>
</MatDialog>
@code
{
    private IList<BloggerListDto> bloggers;
    BloggerEditDto editDto = new BloggerEditDto();
    BloggerListDto listDto;
    string currentBloggerName = "";
    int? currentBloggerId = null;
    int categoryId, sourceType;
    int sort = 0;
    bool isCurrentBloggerReadOnly = false;

    bool InsertOperation;
    string requestUri = "http://localhost:13822/";
    protected async override Task OnInitializedAsync()
    {
        string queryString = "?page=1&limit=10";
        try
        {
            PagedResultDto<BloggerListDto> result = await Http.GetJsonAsync<PagedResultDto<BloggerListDto>>($"{requestUri}api/bloggers{queryString}");
            bloggers = result.Items.ToList();
        }
        catch(HttpRequestException he)
        {
            matToaster.Add(he.Message, MatToastType.Danger, "User Get Failed");
        }
    }

    #region OpenUpdateDialog
    string labelUpsertDialogOkButton, labelUpsertDialogTitle;
    bool UpsertBloggerDialogOpen = false;
    Dictionary<int, string> categoriesSelections = new Dictionary<int, string>();
    Dictionary<int, string> sourceTypesSelections = new Dictionary<int, string>();
    private async Task OpenUpsertBloggerDialog(int? bloggerId = null)
    {
        currentBloggerId = bloggerId;

        InsertOperation = !bloggerId.HasValue;// (roleName == "");

        // Update the UI
        if (InsertOperation)
        {
            labelUpsertDialogTitle = "Create Blogger";
            labelUpsertDialogOkButton = "Create Blogger";
            editDto = new BloggerEditDto();
        }
        else
        {
            labelUpsertDialogTitle = "Edit Blogger";
            labelUpsertDialogOkButton = "Update Blogger";

            editDto = await Http.GetJsonAsync<BloggerEditDto>($"{requestUri}api/bloggers/{bloggerId.Value}");
            //editDto = await _bloggerService.GetBloggerForEditAsync(bloggerId.Value);
        }
        // Retrieve the role
        isCurrentBloggerReadOnly = !bloggerId.HasValue;//(roleName != "");

        // Setup The Categories
        categoriesSelections = await _categoryService.GetNavSelectList();
        sourceTypesSelections = await _enumService.GetSortTypeSelectListAsync();

        this.UpsertBloggerDialogOpen = true;

    }
    #endregion

    #region OpenDeleteDialog
    bool isDeleteBloggerDialogOpen = false;

    public void OpenDeleteDialog(int bloggerId, string bloggerName)
    {
        currentBloggerId = bloggerId;
        currentBloggerName = bloggerName;
        listDto = bloggers.FirstOrDefault(b => b.Id == bloggerId);
        isDeleteBloggerDialogOpen = true;
    }
    #endregion

    #region UpsertBlogger
    public async Task UpsertBloggerAsync()
    {
        try
        {
            if (InsertOperation)
            {
                BloggerListDto result = await Http.PostJsonAsync<BloggerListDto>($"{requestUri}api/bloggers", editDto);
                bloggers.Add(result);
                matToaster.Add("User Created", MatToastType.Success);
            }
            else
            {
                BloggerListDto result = await Http.PutJsonAsync<BloggerListDto>($"{requestUri}api/bloggers/{editDto.Id}", editDto);
                int editIndex = bloggers.IndexOf(bloggers.FirstOrDefault(b => b.Id == editDto.Id));
                bloggers[editIndex] = result;
                matToaster.Add("User Updated", MatToastType.Success);
            }
            UpsertBloggerDialogOpen = false;
        }
        catch (Exception ex)
        {
            matToaster.Add(ex.Message, MatToastType.Danger, "User Upsert Failed");
        }
    }
    #endregion

    #region DeleteBlogger
    public async Task DeleteBloggerAsync()
    {
        try
        {
            HttpResponseMessage response = await Http.DeleteAsync($"{requestUri}api/bloggers/{listDto.Id}");
            isDeleteBloggerDialogOpen = false;
            if (response.StatusCode != System.Net.HttpStatusCode.OK
                && response.StatusCode != System.Net.HttpStatusCode.NoContent)
            {
                matToaster.Add("Blogger Delete Failed", MatToastType.Danger);
                return;
            }

            bloggers.Remove(listDto);
            matToaster.Add("Blogger Deleted", MatToastType.Success);
            // await OnInitializedAsync();
            StateHasChanged();
        }
        catch (Exception ex)
        {
            matToaster.Add(ex.Message, MatToastType.Danger, "User Delete Failed");
        }
    }
    #endregion
}